package com.atao.handle.mybatisplus;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.Date;

/**
 * 字段填充
 */
@Component
@Slf4j
public class MyMetaObjectHandler implements MetaObjectHandler {
    
    private String getCreateBy(MetaObject metaObject) {
        String user = "non-self";
        try {
            Field createBy = metaObject.getOriginalObject().getClass().getDeclaredField("createBy");
            createBy.setAccessible(true);
            user = createBy.get(metaObject.getOriginalObject()).toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return user;
    }
    
    @Override
    public void insertFill(MetaObject metaObject) {
        //Todo 判断用户
        String user = getCreateBy(metaObject);
        this.setFieldValByName("createTime", new Date(), metaObject);
        this.setFieldValByName("createBy",user , metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", user, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String user = getCreateBy(metaObject);
        this.setFieldValByName("updateTime", new Date(), metaObject);
        this.setFieldValByName("updateBy", user, metaObject);
    }
}